import { generateGlobalRoutesAndApis, generateCurrentUserRoutesAndApis } from './generateRoutesAndApis';
import { ROUTE_LOGIN, ROUTE_PERMISSION_DENIED } from '$lib/config/variable';

let allPermissionRoutes = void 0;

const authPermission = async (pathname, cancel) => {
  if (allPermissionRoutes === void 0) {
    let permissionHandles = await fetch('/api/permission-handles');
    permissionHandles = await permissionHandles.json();
    permissionHandles = permissionHandles;
    const handles = permissionHandles.map((item) => item.handle);
    allPermissionRoutes = generateGlobalRoutesAndApis(handles).routes;
  }
  if (!allPermissionRoutes.some(r => pathname.startsWith(r))) return;
  let currenUser = await fetch('/api/account/verify-login');
  currenUser = await currenUser.json();
  if (!currenUser.status) {
    cancel();
    window.location.href = ROUTE_LOGIN;
  }
  const currentUserPermissions = currenUser.data.userinfo.permissions;
  const currentUserHandles = currentUserPermissions.length > 0 ? currentUserPermissions.map((item) => item.handle) : [];
  const currentRoutes = generateCurrentUserRoutesAndApis(currentUserHandles).routes;
  if (!currentRoutes.some(r => pathname.startsWith(r))) {
    cancel();
    window.location.href = ROUTE_PERMISSION_DENIED;
  };
}

export default authPermission;